package com.zsh.spring;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;

public class JDKProxy {
    public static void main(String[] args) {
        //创建接口实现类的代理对象
        Class[] interfaces = {UserDao.class};
        UserDao userDao = new UserDaoImpl();
        UserDao dao = (UserDao) Proxy.newProxyInstance(JDKProxy.class.getClassLoader(), interfaces, new UserDaoProxy(userDao));
        int add = dao.add(1, 2);
        System.out.println(add);
    }
}

//代理对象的代码
class UserDaoProxy implements InvocationHandler{

    //谁的代理对象，把他传进来
    //有参构造
    private Object obj;
    public UserDaoProxy(Object obj){
        this.obj = obj;
    }

    //增强的方法部分
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        //方法之前

        System.out.println("方法之前" + method.getName() + "参数" + Arrays.toString(args));
        //被增强的方法执行
        Object res = method.invoke(obj, args);
        //方法之后
        System.out.println("方法之后" + obj );

        return res;
    }
}
